<script setup>
import { ref } from "vue";
const width1 = ref(100);
const wLeft = ref(2);
const wRight = ref(2);
const isDragEnd = ref(true);
const onDragStart = (type) => {
  isDragEnd.value = true;
  const progressBox = document.querySelector(".progress");
  if (type === "left") {
    progressBox.addEventListener("mousemove", onDragLeft);
    progressBox.removeEventListener("mousemove", onDragRight);
  } else if (type === "right") {
    progressBox.addEventListener("mousemove", onDragRight);
    progressBox.removeEventListener("mousemove", onDragLeft);
  }
  progressBox.addEventListener("mouseup", onDragEnd);
};
const onDragEnd = () => {
  isDragEnd.value = false;
  const progressBox = document.querySelector(".progress");
  progressBox.removeEventListener("mousemove", onDragRight);
  progressBox.removeEventListener("mousemove", onDragLeft);
};
const onDragLeft = (event) => {
  if (isDragEnd.value) {
    const progressBox = document.querySelector(".progress");
    const rect = progressBox.getBoundingClientRect();
    const width = rect.width;
    const offsetX = event.clientX - rect.left;
    let percentage = Math.round((offsetX / width) * 100);
    percentage = Math.max(0, Math.min(percentage, 100));
    wLeft.value = percentage;
    width1.value = 100 - wLeft.value - wRight.value;
  }
};
const onDragRight = (event) => {
  if (isDragEnd.value) {
    const progressBox = document.querySelector(".progress");
    const rect = progressBox.getBoundingClientRect();
    const width = rect.width;
    const offsetX = event.clientX - rect.left;

    const offsetRight = rect.width - offsetX;
    let percentage = Math.round((offsetRight / width) * 100);
    percentage = Math.max(0, Math.min(percentage, 100));
    wRight.value = percentage;
    width1.value = 100 - wLeft.value - wRight.value;
  }
};
</script>

<template>
  <div class="progress">
    <div
      class="left"
      :style="{
        width: wLeft + '%',
      }"
      @mousedown="onDragStart('left')"
    ></div>
    <div
      class="child"
      :style="{
        width: width1 + '%',
      }"
    ></div>
    <div
      class="right"
      :style="{
        width: wRight + '%',
      }"
      @mousedown="onDragStart('right')"
    ></div>
  </div>
</template>

<style scoped>
.progress {
  width: 600px;
  height: 60px;
  background-color: blue;
  border: 1px red solid;
  display: flex;
}
.child {
  background-color: #fff;
  height: 60px;
}
.left.right {
  background-color: #fff;
  height: 60px;
}
</style>
